package cn.vacuumflask.cordova.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.widget.Toast;

import com.dascom.print.SmartPrint;

import cn.vacuumflask.cordova.entity.PrintOrder;


/**
 * Created by huangqx on 2017/10/18.
 */

public class WiFiPrintUtil {


    //打印入库单无条码
    public static void printOrder(final Activity activity, final SmartPrint smartPrint, final PrintOrder printOrder, ProgressDialog progressDialog) {

        if (printOrder == null) {
            printEnd(activity, smartPrint, false, progressDialog);
            return;
        }

        MyThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {

                boolean isSuccess = false;
                int printCount = printOrder.getPrintCount();
                for (int i = 0; i < printCount; i++) {
                    //大
                    double y = 0.2;
                    smartPrint.SetPageLength(1.6f);
                    smartPrint.Print_HLine(2, 0, 0, 0, 0);//一页开始
                    smartPrint.DSSetDirection(0);
                    double x = 1.2;
                    boolean b1 = smartPrint.PrintCode128(0, 30, x, y, 0.5, 30, 30, true, false, printOrder.getBarcode());//制单号条形码
                    boolean b2 = smartPrint.PrintText(0, 30, x, (y += 0.8), 1, 1, "工单号：" + printOrder.getOrderId());
                    String goodsMsg = "货品款号：" + printOrder.getGoodsMsg();
                    boolean b3 = smartPrint.PrintText(0, 30, x, (y += 0.2), 1, 1, goodsMsg);
                    boolean b4 = smartPrint.PrintText(0, 30, x, (y += 0.2), 1, 1, "数量：" + printOrder.getCount());
                    boolean b5 = smartPrint.Print_HLine(3, 0, 0, 0, 0);//一页结束

                    if (b1 && b2 && b3 && b4 && b5) {
                        isSuccess = true;
                    } else {
                        isSuccess = false;
                        break;
                    }
                }

                printEnd(activity, smartPrint, isSuccess, progressDialog);

            }
        });
    }

    //打印结束后的提示
    private static void printEnd(Activity activity, SmartPrint smartPrint, boolean isFinish, ProgressDialog progressDialog) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    Toast.makeText(activity, isFinish ? "打印成功" : "打印失败", Toast.LENGTH_LONG).show();

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (smartPrint != null) {
                        smartPrint.DSCloseWifi();//断开 WIFI 连接
                    }
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                }
            }
        });

    }


}
